package com.itheima.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.itheima.controller.utils.R;
import com.itheima.domain.Book;
import com.itheima.service.IBookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.List;

@RestController
@RequestMapping ("/books")
public class BookController {
    @Autowired
    private IBookService bookService;

//    查询全部
    @GetMapping
    public R getAll(){
        return new R(true,bookService.list());
    }

//    增加数据
    @PostMapping
    public R save(@RequestBody Book book) throws IOException {
//        R r=new R();
//       Boolean flag= bookService.save(book);
//        r.setFlag(flag);

//          模拟的一个异常处理
//        if(book.getName().equals("123")) throw new IOException();


        Boolean flag= bookService.save(book);
       return new R(flag , flag ? "添加成功^_^" : "添加失败-_-!");
    }

//    改动数据---注意传递的是一个对象
    @PutMapping
    public R update(@RequestBody Book book){
        return new R(bookService.updateById(book));
    }

//    根据id删除数据
    @DeleteMapping("{id}")
    public R delete(@PathVariable Integer id){
        return new R(bookService.removeById(id));
    }

//    根据id查询数据
    @GetMapping("{id}")
    public R getById(@PathVariable Integer id){
        return new R(true,bookService.getById(id));
    }

//    分页查询数据
//    @GetMapping("{currentPage}/{pageSize}")
//    public R getPage(@PathVariable int currentPage,@PathVariable int pageSize){
//    IPage<Book> page = bookService.getPage(currentPage,pageSize);
//
//    if (currentPage>page.getPages()){
//        page = bookService.getPage((int)page.getPages(),pageSize);
//    }
//    return new R(page!=null,page);
//    }

//    分页查询数据，并携带参数查询
    @GetMapping("{currentPage}/{pageSize}")
    public R getPage(@PathVariable int currentPage,@PathVariable int pageSize,Book book){
        IPage<Book> page = bookService.getPage(currentPage,pageSize,book);

        if (currentPage>page.getPages()){
            page = bookService.getPage((int)page.getPages(),pageSize,book);
        }
        return new R(page!=null,page);
    }
}
